package cn.wind.xboot.module.web.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.wind.xboot.core.res.ApiResult;
import cn.wind.xboot.framework.domain.PageVo;
import cn.wind.xboot.logic.cli.entity.CliClient;
import cn.wind.xboot.logic.cli.entity.CliInfo;
import cn.wind.xboot.logic.cli.service.ICliClientService;
import cn.wind.xboot.logic.cli.service.ICliInfoService;
import cn.wind.xboot.logic.dto.*;
import cn.wind.xboot.logic.entity.Bank;
import cn.wind.xboot.logic.entity.Store;
import cn.wind.xboot.logic.entity.StoreStaff;
import cn.wind.xboot.logic.entity.VegetableMarket;
import cn.wind.xboot.logic.service.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.bytebuddy.asm.Advice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *商户管理Controller
 * @author WangHao
 * @date 2018-12-29
 */
@Slf4j
@Controller
@RequestMapping("business")
public class BusinessStoreManageController {
    @Autowired
    private IStoreService storeService;
    @Autowired
    private ICliClientService cliClientService;
    @Autowired
    private ICliInfoService cliInfoService;
    @Autowired
    private IBankService bankService;
    @Autowired
    private IVegetableMarketService vegetableMarketService;
    @Autowired
    private IStoreStaffService storeStaffService;
    @Autowired
    private IStoreSteelyardService storeSteelyardService;


    /**
     * 列表展示所有商户
     * @param isEnabled  是否黑名单
     * @param searchName 模糊查询关键字
     */
    @ResponseBody
    @RequestMapping("/list")
    public ApiResult list(PageVo pageVo,String searchName,Integer marketId,Boolean isEnabled,String province,String city,String district){
        Map<String,Object> map = Maps.newHashMap();
        map.put("searchName",searchName);
        map.put("marketId",marketId);
        map.put("isEnabled",isEnabled);
        map.put("province",province);
        map.put("city",city);
        map.put("district",district);
        IPage<CliStoreDto> page = storeService.findByCondition(pageVo.init(),map);
        System.out.println();
        return ApiResult.Custom().success("查询成功").add(page);
    }

    /**
     * 添加主商户
     */
    @RequestMapping("/add")
    @ResponseBody
    public ApiResult add(AddCliStoreDto addCliStoreDto){
        //基本商户信息
        CliClient cliClient = new CliClient();
        //商户扩展信息
        CliInfo cliInfo = new CliInfo();
        //店铺信息
        Store store = new Store();
        //银行卡信息
        Bank bank = new Bank();

        cliClient.setUsername(addCliStoreDto.getUsername());
        //给主商户添加默认密码 abc12345
        cliClient.setPassword("abc12345");
        cliClientService.saveOrUpdate(cliClient);

        cliInfo.setRealName(addCliStoreDto.getRealName());
        cliInfo.setMobile(addCliStoreDto.getMobile());
        cliInfo.setIdCard(addCliStoreDto.getIdCard());
        cliInfo.setNickName(addCliStoreDto.getNickName());
        cliInfo.setCliId(cliClient.getId());
        cliInfo.setGender(addCliStoreDto.getGender());
        cliInfo.setBirthday(addCliStoreDto.getBirthday());
        cliInfo.setUserType("1");
        cliInfoService.saveOrUpdate(cliInfo);

        bank.setCliId(cliClient.getId());
        bank.setBankCard(addCliStoreDto.getBankCard());
        bankService.saveOrUpdate(bank);

        store.setCliId(cliClient.getId());
        store.setName(addCliStoreDto.getStoreName());
        store.setMarketName(vegetableMarketService.getById(addCliStoreDto.getMarketId() ).getName());
        if (storeService.findByNo(addCliStoreDto.getStoreNo()) != null){
            return ApiResult.Custom().failure( "该摊位号已存在,请重新填写!" );
        }else {
            store.setNo( addCliStoreDto.getStoreNo() );
            store.setVId( addCliStoreDto.getMarketId() );
            storeService.saveOrUpdate( store );
        }
        return ApiResult.Custom().success( "添加商户成功" );
    }

    /**
     * 修改主商户
     */
    @RequestMapping("/modify")
    @ResponseBody
    public ApiResult modify(CliStoreDto cliStoreDto){
        //CliClient cliClient = cliClientService.findCliById(cliStoreDto.getCliId());
        CliInfo cliInfo = cliInfoService.selectByCliId(cliStoreDto.getCliId());
        cliInfo.setCliId(cliStoreDto.getCliId());
        cliInfo.setRealName(cliStoreDto.getRealName());
        cliInfo.setMobile(cliStoreDto.getPhone());
        cliInfo.setNickName(cliStoreDto.getNickName());
        cliInfoService.saveOrUpdate(cliInfo);

        return ApiResult.Custom().success("修改成功!");
    }

    /**
     * 删除主商户
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ApiResult delete(CliClient cliClient){
        //删除商户的店铺
        storeService.removeById(storeService.findByCid(cliClient.getId()).getId());
        //删除商户的银行卡信息
        bankService.removeById(bankService.findByCid(cliClient.getId()).getId());
        //删除商户的个人扩展信息
        cliInfoService.delById(cliInfoService.selectByCliId(cliClient.getId()).getId());
        //删除商户个人信息
        cliClientService.removeById(cliClient.getId());
        return ApiResult.Custom().success("删除成功!");
    }

    /**
     * 拉黑主商户
     */
    @RequestMapping("/prohibit")
    @ResponseBody
    public ApiResult prohibit(CliClient cliClient){
            cliClientService.saveOrUpdate(cliClient);
            return ApiResult.Custom().success("拉黑商户成功!");
    }

    /**
     * 主商户详情
     */
    @RequestMapping("/info")
    @ResponseBody
    public ApiResult BusinessInfo(Long id){
        CliStoreDto cliStoreDto = cliClientService.findById(id);
        Store store = storeService.findByCid(id);
        cliStoreDto.setStoreNo(store.getNo());
        VegetableMarket vegetableMarket = vegetableMarketService.getById(store.getVId());
        cliStoreDto.setMarketName(vegetableMarket.getName());
        Bank bank = bankService.findByCid(id);
        cliStoreDto.setBankCard(bank==null ? "" : bank.getBankCard());
        return ApiResult.Custom().success( ).add(cliStoreDto);
    }

    /**
     * 给主商户的店铺添加店员
     */
    @RequestMapping("/addStoreStaff")
    @ResponseBody
    public ApiResult addStoreStaff(AddStoreStaffDto addStoreStaffDto){
        //店员
        StoreStaff storeStaff = new StoreStaff();
        //店员用户
        CliClient cliClient = new CliClient();
        //店员扩展信息
        CliInfo cliInfo = new CliInfo();
        //默认手机号为用户名
        cliClient.setUsername(addStoreStaffDto.getMobile());
        cliClient.setPassword(addStoreStaffDto.getPassword());
        cliClientService.saveOrUpdate(cliClient);
        cliInfo.setRealName(addStoreStaffDto.getRealName());
        cliInfo.setMobile(addStoreStaffDto.getMobile());
        cliInfo.setCliId(cliClient.getId());
        cliInfo.setUserType("3");
        cliInfo.setGender(addStoreStaffDto.getGender());
        cliInfoService.saveOrUpdate(cliInfo);
        storeStaff.setCliId(cliClient.getId());
        /**
         * 绑定店铺
         */
        Store store = storeService.findByName(addStoreStaffDto.getStoreName());
        storeStaff.setSId(store.getId());
        storeStaffService.saveOrUpdate(storeStaff);
        return ApiResult.Custom().success("添加员工成功!");
    }

    /**
     * 主商铺-店员列表
     * @param storeNo 店铺摊位号
     */
    @RequestMapping("/storeStaffList")
    @ResponseBody
    public ApiResult storeStaffList(PageVo pageVo,String storeNo){
        Map<String,Object> map = Maps.newHashMap();
        map.put("storeNo",storeNo);
        IPage<StoreStaffDto> page = storeStaffService.findStoreStaffList(pageVo.init(),map);
        return ApiResult.Custom().success().add(page);
    }


    /**
     * 主商户-店员修改
     */
    @RequestMapping("/storeStaffEdit")
    @ResponseBody
    public ApiResult editStoreStaff(AddStoreStaffDto addStoreStaffDto){
        //店员
        StoreStaff storeStaff = storeStaffService.getById(addStoreStaffDto.getSubStoreStaffId());
        //店员用户
        CliClient cliClient = cliClientService.findCliById(storeStaff.getCliId());
        //店员扩展信息
        CliInfo cliInfo = cliInfoService.selectByCliId(storeStaff.getCliId());
        if (addStoreStaffDto.getPassword() != null && !addStoreStaffDto.getPassword().equals("")){
            cliClient.setPassword(addStoreStaffDto.getPassword());
        }
        cliClientService.saveOrUpdate(cliClient);
        if (addStoreStaffDto.getMobile()!=null && !addStoreStaffDto.getMobile().equals("")){
            cliInfo.setMobile(addStoreStaffDto.getMobile());
        }
       // cliInfo.setCliId(cliClient.getId());
        cliInfoService.saveOrUpdate(cliInfo);
       // storeStaff.setCliId(cliClient.getId());
        //storeStaffService.saveOrUpdate(storeStaff);
        return ApiResult.Custom().success("店员修改成功!");
    }

    /**
     * 主商户-店员删除
     */
    @RequestMapping("/storeStaffDel")
    @ResponseBody
    public ApiResult delStoreStaff(Long storeStaffId){
        storeStaffService.removeById(storeStaffId);
        return ApiResult.Custom().success("店员删除成功!");
    }

    /**
     * 主商户电子秤列表
     */
    @RequestMapping("/getStoreSteelyardList")
    @ResponseBody
    public ApiResult getStoreSteelyardList(PageVo pageVo,String storeNo){
        Map<String,Object> map = Maps.newHashMap();
        map.put("storeNo",storeNo);
        IPage<StoreSteelyardDto> page = storeSteelyardService.getStoreSteelyardList(pageVo.init(),map);
        return ApiResult.Custom().success( ).add(page);
    }

    /**
     * 添加子店铺
     */
    @RequestMapping("/subStore/add")
    @ResponseBody
    public ApiResult addSubStore(AddCliStoreDto addCliStoreDto){
        //基本商户信息
        CliClient cliClient = new CliClient();
        //商户扩展信息
        CliInfo cliInfo = new CliInfo();
        //店铺信息
        Store store = new Store();
        //银行卡信息
        Bank bank = new Bank();
        //给子店铺用户默认手机号设为用户名
        cliClient.setUsername(addCliStoreDto.getMobile());
        //默认密码  123456
        cliClient.setPassword("123456");
        cliClientService.saveOrUpdate(cliClient);

        //上级商户id
        cliInfo.setPId(addCliStoreDto.getDaCliId());
        cliInfo.setRealName(addCliStoreDto.getRealName());
        cliInfo.setMobile(addCliStoreDto.getMobile());
        cliInfo.setIdCard(addCliStoreDto.getIdCard());
        cliInfo.setUserType("1");
        //商户名称
        cliInfo.setNickName(addCliStoreDto.getNickName());
        cliInfo.setCliId(cliClient.getId());
        cliInfo.setGender(addCliStoreDto.getGender());
        cliInfo.setBirthday(addCliStoreDto.getBirthday());
        cliInfoService.saveOrUpdate(cliInfo);
        //银行卡
        bank.setCliId(cliClient.getId());
        bank.setBankCard(addCliStoreDto.getBankCard());
        bankService.saveOrUpdate(bank);
        //店铺
        store.setCliId(cliClient.getId());
        store.setName(addCliStoreDto.getStoreName());
        store.setMarketName(vegetableMarketService.getById(addCliStoreDto.getMarketId() ).getName());
        if (storeService.findByNo(addCliStoreDto.getStoreNo()) != null){
            return ApiResult.Custom().failure( "该摊位号已存在,请重新填写!" );
        }else {
            store.setNo( addCliStoreDto.getStoreNo() );
            store.setVId( addCliStoreDto.getMarketId() );
            storeService.saveOrUpdate( store );
        }
        return ApiResult.Custom().success("添加子商铺成功!");
    }

    /**
     * 子店铺-修改
     */
    @RequestMapping("/subStore/modify")
    @ResponseBody
    public ApiResult modify(Long cliId,Long sId,AddCliStoreDto addCliStoreDto){
        //基本商户信息
        CliClient cliClient = cliClientService.findCliById(cliId);
        //商户扩展信息
        CliInfo cliInfo = cliInfoService.selectByCliId(cliId);
        //店铺信息
        Store store = storeService.getById(sId);
        //商户名称
        if (addCliStoreDto.getNickName() != null){
            cliInfo.setNickName(addCliStoreDto.getNickName());
        }
        if (addCliStoreDto.getMobile() != null){
            cliInfo.setMobile(addCliStoreDto.getMobile());
        }
        if (addCliStoreDto.getStoreNo() != null){
            store.setNo(addCliStoreDto.getStoreNo());
        }
        if (addCliStoreDto.getStoreName() != null){
            store.setName(addCliStoreDto.getStoreName());
        }
        cliInfoService.saveOrUpdate(cliInfo);
        store.setCliId(cliClient.getId());
        storeService.saveOrUpdate(store);
        return ApiResult.Custom().success("修改子店铺成功!");
    }

    /**
     * 子店铺-删除
     */
    @RequestMapping("/subStore/delete")
    @ResponseBody
    public ApiResult delete(Long cliId){
            Store store = storeService.findByCid(cliId);
            CliInfo cliInfo = cliInfoService.selectByCliId(cliId);
            cliClientService.removeById(cliId);
            cliInfoService.delById(cliInfo.getId());
            storeService.removeById(store.getId());
            return ApiResult.Custom().success("子店铺删除成功!");
    }


    /**
     * 主商户-子商铺列表
     */
    @RequestMapping("/subStore/List")
    @ResponseBody
    public ApiResult subStoreList(PageVo pageVo,Long cliPid){
        Map<String,Object> map = Maps.newHashMap();
        //子店铺上级商户的用户扩展id
        //Long clinfoPid = cliInfoService.selectByCliId(cliPid).getId();
        map.put("pId",cliPid);
        IPage<SubStoreDto> page = storeService.findSubStoreList(pageVo.init(),map);
        return ApiResult.Custom().success( ).add(page);
    }

    /**
     * 子店铺详情
     * @param cliId  该子店铺归属人的用户id
     */
    @RequestMapping("/subStore/info")
    @ResponseBody
    public ApiResult info(Long cliId){
        SubStoreDto subStoreDto = storeService.findSubStoreInfo(cliId);
        return ApiResult.Custom().success().add(subStoreDto);
    }

    /**
     * 子商铺-店员添加
     */
    @RequestMapping("/storeStaff/add")
    @ResponseBody
    public ApiResult storeStaffAdd(AddStoreStaffDto addStoreStaffDto){
        //店员
        StoreStaff storeStaff = new StoreStaff();
        //店员用户
        CliClient cliClient = new CliClient();
        //店员扩展信息
        CliInfo cliInfo = new CliInfo();
        //默认手机号为用户名
        cliClient.setUsername(addStoreStaffDto.getMobile());
        cliClient.setPassword(addStoreStaffDto.getPassword());
        cliClientService.saveOrUpdate(cliClient);
        cliInfo.setRealName(addStoreStaffDto.getRealName());
        cliInfo.setMobile(addStoreStaffDto.getMobile());
        cliInfo.setCliId(cliClient.getId());
        cliInfo.setUserType("3");
        cliInfo.setGender(addStoreStaffDto.getGender());
        cliInfoService.saveOrUpdate(cliInfo);
        storeStaff.setCliId(addStoreStaffDto.getCliId());
        /**
         * 绑定店铺
         */
        Store store = storeService.findByName(addStoreStaffDto.getStoreName());
        storeStaff.setSId(store.getId());
        storeStaffService.saveOrUpdate(storeStaff);
        return ApiResult.Custom().success("店员添加成功!");
    }

    /**
     * 子店铺-店员-修改
     */
    @RequestMapping("/storeStaff/edit")
    @ResponseBody
    public ApiResult storeStaffEdit(Long cliId,Long storeStaffId,AddStoreStaffDto addStoreStaffDto){
        //店员
        StoreStaff storeStaff = storeStaffService.getById(storeStaffId);
        //店员用户
        CliClient cliClient = cliClientService.findCliInfo(cliId);
        //店员扩展信息
        CliInfo cliInfo = cliClient.getCliInfo();
        if (addStoreStaffDto.getPassword() != null && !addStoreStaffDto.getPassword().equals("")){
            cliClient.setPassword(addStoreStaffDto.getPassword());
        }
        cliClientService.saveOrUpdate(cliClient);
        if (addStoreStaffDto.getRealName() != null){
            cliInfo.setRealName(addStoreStaffDto.getRealName());
        }
        if (addStoreStaffDto.getMobile()!=null && !addStoreStaffDto.getMobile().equals("")){
            cliInfo.setMobile(addStoreStaffDto.getMobile());
        }
        cliInfo.setCliId(cliClient.getId());
        if (addStoreStaffDto.getGender()!=null && !addStoreStaffDto.getGender().equals("")){
            cliInfo.setGender(addStoreStaffDto.getGender());
        }
        cliInfoService.saveOrUpdate(cliInfo);
        storeStaff.setCliId(cliClient.getId());
        storeStaffService.saveOrUpdate(storeStaff);
        return ApiResult.Custom().success("店员修改成功!");
    }

    /**
     * 子店铺-店员-删除
     */
    @RequestMapping("/storeStaff/del")
    @ResponseBody
    public ApiResult storeStaffDel(){

        return ApiResult.Custom().success("店员删除成功!");
    }

    /**
     * 子店铺-店员-列表
     */
    @RequestMapping("/storeStaff/list")
    @ResponseBody
    public ApiResult list(PageVo pageVo,Long cliId){
        Map<String,Object> map = Maps.newHashMap();
        map.put("cliId",cliId);
        IPage<StoreStaffDto> page = storeStaffService.findStoreStaffList(pageVo.init(),map);
        return ApiResult.Custom().success().add(page);
    }


    /**
     * 批量导入
     */
    @RequestMapping("/importXls")
    @ResponseBody
    public ApiResult importXls(MultipartHttpServletRequest multipart) throws IOException {
        //记录导入
        MultipartFile file = multipart.getFile("file");
        ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
        List<Map<String, Object>> readAll = reader.readAll();
        List<VegetableMarket> vegetableMarkets = new ArrayList<>();
      /*  for (Map map : readAll) {
            VegetableMarket market = new VegetableMarket();
            market.setName(map.get( MarketModelEnum.name.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.name.getTypeName()).toString());
            market.setProvince(map.get(MarketModelEnum.province.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.province.getTypeName()).toString());
            market.setCity(map.get(MarketModelEnum.city.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.city.getTypeName()).toString());
            market.setDistrict(map.get(MarketModelEnum.district.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.district.getTypeName()).toString());
            market.setAddress(map.get(MarketModelEnum.address.getTypeName()) == null ? "" :
                    map.get(MarketModelEnum.address.getTypeName()).toString());
            vegetableMarkets.add(market);
        }*/
        vegetableMarketService.saveOrUpdateBatch(vegetableMarkets);
        return ApiResult.Custom().success("导入完成");
    }

    /**
     * 菜市场管理-导入模板下载
     */
    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletRequest req, HttpServletResponse resp) {
        try {
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("excel/detail.xlsx");
            System.out.println("文件流："+in.available());
            req.setCharacterEncoding("UTF-8");
            //获取要下载的文件名
            String name = "企业导入模板.xlsx";
            //第一步：设置响应类型
            //应用程序强制下载
            resp.setContentType("application/force-download");
            //设置响应头，对文件进行url编码
            name = URLEncoder.encode(name, "UTF-8");
            resp.setHeader("Content-Disposition", "attachment;filename=" + name);
            resp.setContentLength(in.available());

            //第三步：老套路，开始copy
            OutputStream out = resp.getOutputStream();
            byte[] b = new byte[1024];
            int len = 0;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            out.flush();
            out.close();
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 批量导出
     */
}
